package com.ld.collegetask;

import android.Manifest;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.databinding.ActivityMemberEditBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.CameraPopup;
import com.ld.collegetask.utils.PicassoImageLoader;
import com.ld.collegetask.utils.SharePreference;
import com.ld.collegetask.utils.ToastUtil;
import com.squareup.picasso.Picasso;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by yilan on 18/3/6.
 */

public class MemberEditActivity extends BaseActivity {
    private final String TAG = "MemberEditActivity_1";
    private ActivityMemberEditBinding binding;
    private GalleryConfig galleryConfig;
    private List<String> path = new ArrayList<>();
    private String ReaName = "";
    private String UserImg = "";
    private PromptDialog promptDialog;
    private Integer userId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_member_edit);
        //设置标题
        setTitleView(this, binding.ilTitle, true, true, false, false);
        setTitle("个人资料");
        ico.setVisibility(View.INVISIBLE);
        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();
        showData();
    }

    private void showData() {
        promptDialog = new PromptDialog(this);
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.ld.collegetask.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
        binding.ivUserImage.setOnClickListener(this);
        ReaName = getIntent().getStringExtra("ReaName");
        UserImg = getIntent().getStringExtra("UserImg");
        binding.memberRealname.setText(ReaName);
        Picasso.with(mActivity)
                .load(AppApplication.server+UserImg)
                .fit()
                .placeholder(R.drawable.user_img)
                .error(R.drawable.user_img)
                .into(binding.ivUserImage);
    }

    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            Log.i(TAG, "onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            Log.i(TAG, "onSuccess: 返回数据" + photoList.get(0));
            File file = new File(photoList.get(0));
            member_validateImg(file);
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "onCancel: 取消");
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "onFinish: 结束");
        }

        @Override
        public void onError() {
            Log.i(TAG, "onError: 出错");
        }
    };

    @Override
    public void loading() {
    }

    /**
     * 选择相册、照像机
     */
    private void choosePhotoOrCamera() {
        new CameraPopup(mActivity, binding.ivUserImage, new CameraPopup.OnCallClickEvent() {
            @Override
            public void onCallClick(int position) {
                if (position == 0) {
                    galleryConfig = new GalleryConfig.Builder()
                            .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                            .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                            .provider("com.ld.collegetask.fileprovider")   // provider(必填)
                            .pathList(path)                         // 记录已选的图片
                            .multiSelect(false)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                            .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                            .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                            .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                            .filePath("/Gallery/Pictures")          // 图片存放路径
                            .build();
                    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    if (permissions.length == 1) {
                                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(mActivity);
                                    }
                                }

                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, Manifest.permission.WRITE_EXTERNAL_STORAGE
                    );
                } else {
                    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    if (permissions.length == 1) {
                                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(mActivity);
                                    }
                                }

                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, Manifest.permission.CAMERA
                    );
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_user_image:
                choosePhotoOrCamera();
                break;
        }
    }

    private void member_validateImg(final File file) {
//        http://www.jb51.net/article/107273.htm
        RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, userId+"");
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("pictureFile", file.getName(), requestFile);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<ResponseBody> call = requestSerives.member_register_user_img(description,body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                String json = "";
                try {
                    json = response.body().source().readString(Charset.forName("UTF-8"));
                    Log.v("Upload",json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(json, BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    ToastUtil.showLong(mActivity,"上传成功");
                    promptDialog.dismiss();
                    Picasso.with(mActivity)
                            .load(file)
                            .fit()
                            .placeholder(R.drawable.shuohsuojia)
                            .error(R.drawable.shuohsuojia)
                            .into(binding.ivUserImage);
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastUtil.showLong(mActivity,"上传失败");
                promptDialog.dismiss();
            }
        });
    }
}
